package com.bit.net.component.data.server;

import com.bit.net.RequestCallback;
import com.bit.net.RequestContext;
import com.bit.net.Request;
import com.bit.net.Handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * self-protocal-HandlerServiceFaced
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/10/11 上午 09:59
 */
@Service
public class DataHandlerServiceFaced {


    @Autowired
    private List<Handler> handlerList;

    @Autowired
    @Qualifier("bizWorkers")
    private Executor executor;

    public void handleRequest(RequestContext requestContext, RequestCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Request payload = requestContext.getPayload();
                Handler handler = getSuitableHandler(payload.getClass());
                if (handler != null)
                    handler.handleRequest(requestContext);
                callback.callback(requestContext);
            }
        });
    }

    private Handler getSuitableHandler(Class<? extends Request> clazz) {
        for (Handler handler : handlerList) {
            if (handler.isSupported(clazz))
                return handler;
        }
        return null;
    }


}
